package org.vgou.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.annotations.Param;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.vgou.dao.IBaseDao;
import org.vgou.model.Location;
import org.vgou.service.ILocationService;

/**
 * 
 * Copyright (c) 2011, vgou <br>
 * All rights reserved.<br>
 * 
 * @since 2011-12-1
 * @author <a href="mailto:jason.hxx@gmail.com">jason</a>
 * @version Id: LocationServiceImpl.java
 * @comment 地区服务类
 * 
 */
@Component("locationService")
@RemoteProxy(name = "LocationRemote", creator = SpringCreator.class, creatorParams = { @Param(name = "beanName", value = "LocationServiceImpl") })
public class LocationServiceImpl implements ILocationService {

	protected final Log logger = LogFactory.getLog(getClass());
	@Resource
	private IBaseDao baseDao;

	/**
	 * 创建地区记录
	 * 
	 * @param location
	 * @param parentID
	 * @return
	 * @throws Exception
	 */
	public long create(Location location, long parentID) throws Exception {
		long id = 0;
		if (location == null)
			return id;
		if(parentID > 0){
			Location parent = getById(parentID);
			location.setParent(parent);
		}
		try {
			id = (Long) baseDao.create(location);
		} catch (Exception e) {
			logger.error("创建地区失败：" + e.getMessage());
		}
		return id;
	}

	/**
	 * 修改地区记录
	 * 
	 * @param location
	 * @return
	 * @throws Exception
	 */
	public int update(Location location) throws Exception {
		int result = -1;
		if (location == null)
			return result;
		try {
			baseDao.update(location);
			result = 1;
		} catch (Exception e) {
			logger.error("修改地区记录失败：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 删除地区记录
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RemoteMethod
	public int del(long id) throws Exception {
		int result = -1;
		if (id <= 0)
			return result;
		try {
			Location location = getById(id);
			if (location != null)
				baseDao.delete(location);
			result = 1;
		} catch (Exception e) {
			logger.error("删除地区记录失败：" + e.getMessage());
		}
		return result;
	}
	
	/**
	 * 批量删除地区记录
	 * @param idsStr
	 * @return
	 * @throws Exception
	 */
	@RemoteMethod
	public int batchDel(String idsStr) throws Exception{
		int result = -1;
		String[] ids = idsStr.split(",");
		if(ids.length == 0)
			return result;
		try {
			for(int i=0; i<ids.length; i++){
				long id = Long.valueOf(ids[i]);
				Location location = getById(id);
				if (location != null)
					baseDao.delete(location);
			}
			result = 1;
		} catch (Exception e) {
			logger.error("批量删除地区记录失败：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 根据地区ID取得地区记录
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public Location getById(long id) throws Exception {
		Location location = null;
		if (id <= 0)
			return location;
		try {
			location = (Location) baseDao.getByPk(Location.class, id);
		} catch (Exception e) {
			logger.error("根据地区ID取得地区记录失败：" + e.getMessage());
		}
		return location;
	}

	/**
	 * 取得指定条件下的地区数目
	 * 
	 * @param locationName
	 *            地区名称
	 * @param parentID
	 *            父级ID
	 * @return
	 * @throws Exception
	 */
	public int getAllCount(String locationName, long parentID) throws Exception {
		int count = 0;
		Criteria c = baseDao.getCriteria(Location.class);
		if (locationName != null && !"".equals(locationName)) {
			c.add(Restrictions.eq("name", locationName));
		}
		if(parentID <= 0){
			c.add(Restrictions.isNull("parent"));
		}else{
			c.add(Restrictions.eq("parent.id", parentID));
		}
		c.setProjection(Projections.rowCount());
		count = ((Number) c.uniqueResult()).intValue();
		return count;
	}

	/**
	 * 取得指定条件下的地区集合
	 * 
	 * @param locationName
	 *            地区名称
	 * @param parentID
	 *            父级ID            
	 * @param orderBy
	 *            排序属性
	 * @param isAsc
	 *            是否升序
	 * @param startPage
	 *            分页开始索引
	 * @param pageSize
	 *            每页显示数目
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<Location> getAll(String locationName, long parentID,
			String orderBy, boolean isAsc, int startPage, int pageSize)
			throws Exception {
		List<Location> LocationList = null;
		try {
			DetachedCriteria c = DetachedCriteria.forClass(Location.class);
			if (locationName != null && !"".equals(locationName)) {
				c.add(Restrictions.eq("name", locationName));
			}
			if(parentID <= 0){
				c.add(Restrictions.isNull("parent"));
			}else{
				c.add(Restrictions.eq("parent.id", parentID));
			}
			orderBy = (orderBy == null || "".equals(orderBy)) ? "id" : orderBy;
			if (isAsc) {
				c.addOrder(Order.asc(orderBy));
			} else {
				c.addOrder(Order.desc(orderBy));
			}
			LocationList = baseDao.findByCriteria(c, startPage, pageSize);
		} catch (Exception e) {
			logger.error("取得指定条件下的地区集合失败：" + e.getMessage());
		}
		return LocationList;
	}

}
